package com.drcoffee.drcoffeemall.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class EncipherPassUtil {

    private static final String ALGORITHM = "AES";
    // 密钥，可以自定义
    private static final String KEY = "D2r0hfdgderrh16Cof(q)+**c_off*ee";

    /* 加密 */
    public static String encrypt(String password) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(password.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /* 解密 */
    public static String decrypt(String encryptedPassword) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
//        String password = "201609";
//        String encryptedPassword = encrypt(password);
//        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt("ECjZ0iNCGtaO/T12Sg7Efg==");
        System.out.println("Decrypted password: " + decryptedPassword);
    }
}
